package com.ddtech.business.room.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ddtech.business.common.BaseService;
import com.ddtech.business.config.WebSocketOnLineServer;
import com.ddtech.business.config.WebSocketRoomServer;
import com.ddtech.business.config.WebsocketConstant;
import com.ddtech.business.room.dto.OnSystemUser;
import com.ddtech.business.room.entity.Room;
import com.ddtech.business.room.mapper.RoomMapper;
import com.ddtech.business.room.query.RoomQuery;
import com.ddtech.business.room.service.RoomService;
import com.ddtech.business.vrTask.entity.VrTask;
import com.ddtech.business.vrTask.service.VrTaskService;
import com.ddtech.exception.BadRequestException;
import com.ddtech.utils.PageUtil;
import com.ddtech.utils.SecurityUtils;
import com.ddtech.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @version v1.0
 * @ClassName:RoomServiceImpl description：
 * @author:wei_zhang(xiao)
 * @date: 2024-11-15 16:09
 */
@Service
public class RoomServiceImpl  extends BaseService<RoomMapper, Room>  implements RoomService {

    @Value("${jwt.onSystem}")
    private String onSystemKey;

    @Value("${jwt.expiration}")
    private Long expiration;

    @Autowired
    private VrTaskService vrTaskService;

    @Autowired
    private WebSocketOnLineServer webSocketServer;

    @Autowired
    private WebSocketRoomServer webSocketRoomServer;

    private final RedisTemplate redisTemplate;

    public RoomServiceImpl(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    @Override
    public String create(Room room) {
        if(StringUtils.isNotEmpty(room.getTaskId())){
           VrTask vrTask = vrTaskService.getById(room.getTaskId());
           if(vrTask!=null){
               room.init();
               room.setStatus(0);
               room.setCreateUserName(SecurityUtils.getName());
               room.setCreateUserId(SecurityUtils.getUserId());
               this.saveOrUpdate(room);
           }else{
               throw new BadRequestException("该任务不存在，不允许创建房间。");
           }
        }
        return room.getId();
    }

    @Override
    public void update(Room room) {
        if(StringUtils.isEmpty(room.getId())){
            throw new BadRequestException("房间不存在，请先创建。");
        }
        Room oldRoom=this.getById(room.getId());
        if (oldRoom==null) {
            throw new BadRequestException("房间不存在，请先创建。");
        }
        oldRoom.setRoomInfo(room.getRoomInfo());
        oldRoom.init();
        this.saveOrUpdate(oldRoom);

        List<Room> ls =this.list();
        JSONObject json = new JSONObject();
        json.put("type", WebsocketConstant.ROOM_MESSAGE);
        json.put("data",ls);
        //推送房间消息
        webSocketRoomServer.sendInfo(json.toString());
        //webSocketRoomServer.sendInfo(JSON.toJSONString(ls));
    }

    @Override
    public void startRoom(String id) {
        Room room = this.getById(id);
        if(room!=null){
            room.setStatus(1);
            this.saveOrUpdate(room);
        }
    }

    @Override
    public void del(String id) {
        this.removeById(id);
        List<Room> ls =this.list();
        JSONObject json = new JSONObject();
        json.put("type", WebsocketConstant.ROOM_MESSAGE);
        json.put("data",ls);
        //推送房间消息
        webSocketRoomServer.sendInfo(json.toString());
    }

    @Override
    public void joinSystem() {
        OnSystemUser onSystemUser = new OnSystemUser(SecurityUtils.getUserId(),SecurityUtils.getName(),"");
        redisTemplate.opsForValue().set(onSystemKey + SecurityUtils.getUserId(), onSystemUser);
        redisTemplate.expire(onSystemKey + SecurityUtils.getUserId(),expiration, TimeUnit.MILLISECONDS);
        //发送在线人数消息
        JSONObject json = new JSONObject();
        json.put("type", WebsocketConstant.TRAIN_MESSAGE);
        json.put("data",this.getOnSystemUser());
        webSocketServer.sendInfo(json.toString());
    }

    @Override
    public void leaveSystem() {
        redisTemplate.delete(onSystemKey + SecurityUtils.getUserId());
        //发送在线人数消息
        JSONObject json = new JSONObject();
        json.put("type", WebsocketConstant.TRAIN_MESSAGE);
        json.put("data",this.getOnSystemUser());
        webSocketServer.sendInfo(json.toString());
    }

    @Override
    public int getOnSystemUser() {
        List<String> keys = new ArrayList<>(redisTemplate.keys(onSystemKey + "*"));
        Collections.reverse(keys);
        List<OnSystemUser> onlineUsers = new ArrayList<>();
        for (String key : keys) {
            OnSystemUser onSystemUser = (OnSystemUser) redisTemplate.opsForValue().get(key);
            onlineUsers.add(onSystemUser);
        }
        if (onlineUsers!=null && onlineUsers.size()>0){
            return onlineUsers.size();
        }
        return 0;
    }

    @Override
    public Object pageList(RoomQuery roomQuery) {
        IPage<Room> page = this.page(roomQuery.populatePage(), roomQuery.autoWrapper());
        return PageUtil.toPage(page.getRecords(), page.getTotal());
    }

    @Override
    public Object list(RoomQuery roomQuery) {
        return this.list(roomQuery.autoWrapper());
    }
}
